package tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class ChangePdf {
	private String inputPath;
	private String outputPath;
	private int pageCount;
	private ArrayList<BufferedImage> imageList;
	private PDDocument doc;
	private List pages;
	
	public ChangePdf(String str) throws IOException{
		inputPath = str;
		doc = PDDocument.load(inputPath);
		pageCount = doc.getNumberOfPages();
		pages = doc.getDocumentCatalog().getAllPages();
	}
	
	/**
	 * This method is used
	 * @return
	 * @throws IOException
	 */
	public ArrayList<BufferedImage> changePdfToImage() throws IOException{
		//PDDocument doc = PDDocument.load(inputPath);
		//pageCount = doc.getNumberOfPages();
		//List pages = doc.getDocumentCatalog().getAllPages();
		imageList = new ArrayList<BufferedImage>();
		for(int i = 0;i < pages.size();i++){
			PDPage page = (PDPage)pages.get(i);
			BufferedImage image = page.convertToImage();
			imageList.add(image);
			
			/*Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
			ImageWriter writer = (ImageWriter)iter.next();
			File outFile = new File("C:/"+i+".jpg");
			FileOutputStream out = new FileOutputStream(outFile);
			ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
			writer.setOutput(outImage);
			writer.write(new IIOImage(image, null, null));*/
		}
		doc.close();
		System.out.println("over");
		return imageList;
	}
	
	public BufferedImage getPageByImage(int index) throws IOException{
		PDPage page = (PDPage)pages.get(index);
		BufferedImage image = page.convertToImage();
		return image;
	}
	
	public void writeJpgToFiles(String str) throws IOException{
		outputPath = str;
		for(int i = 0;i < imageList.size();i++){
			Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
			ImageWriter writer = (ImageWriter)iter.next();
			File outFile = new File(outputPath+i+".jpg");
			System.out.println(outputPath+i+".jpg");
			FileOutputStream out = new FileOutputStream(outFile);
			ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
			writer.setOutput(outImage);
			writer.write(new IIOImage(imageList.get(i), null, null));
		}
		
	}

}

